<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="text-center mb-8">
      <h1 class="text-4xl font-bold text-white mb-4">影流播放器</h1>
      <p class="text-gray-400 text-lg">万能跨平台媒体播放器</p>
    </div>

    <!-- 三行URL输入 -->
    <div class="max-w-4xl mx-auto space-y-6">
      <!-- 第一行：单条直链播放 -->
      <div class="card p-6">
        <h2 class="text-xl font-semibold text-white mb-4">单条直链播放</h2>
        <div class="flex gap-4">
          <input
            v-model="singleUrl"
            type="url"
            placeholder="输入视频直链URL（支持http/https/magnet/ed2k）"
            class="input-primary flex-1"
            @keyup.enter="playSingle"
          />
          <button @click="playSingle" class="btn-primary whitespace-nowrap">
            立即播放
          </button>
        </div>
        <div class="mt-2 text-sm text-gray-400">
          支持格式：MP4, WebM, MKV, AVI, MOV, M3U8, 云盘直链等
        </div>
      </div>

      <!-- 第二行：批量网页视频列表 -->
      <div class="card p-6">
        <h2 class="text-xl font-semibold text-white mb-4">批量网页视频列表</h2>
        <div class="space-y-4">
          <div class="flex gap-4">
            <input
              v-model="batchUrl"
              type="url"
              placeholder="输入网页URL或批量视频链接"
              class="input-primary flex-1"
              @keyup.enter="addToBatch"
            />
            <button @click="addToBatch" class="btn-secondary">
              添加
            </button>
          </div>
          
          <div v-if="batchItems.length > 0" class="space-y-2">
            <div class="flex justify-between items-center">
              <span class="text-sm text-gray-400">{{ batchItems.length }} 个视频</span>
              <button @click="clearBatch" class="text-sm text-red-400 hover:text-red-300">
                清空
              </button>
            </div>
            
            <div class="max-h-64 overflow-y-auto space-y-2">
              <div
                v-for="item in batchItems"
                :key="item.id"
                class="flex items-center justify-between bg-gray-700 p-3 rounded"
              >
                <span class="text-sm text-gray-300 truncate flex-1">{{ item.url }}</span>
                <button @click="removeFromBatch(item.id)" class="text-red-400 hover:text-red-300 ml-2">
                  <i class="fas fa-times"></i>
                </button>
              </div>
            </div>
            
            <button @click="playBatch" class="btn-primary w-full">
              播放全部
            </button>
          </div>
        </div>
      </div>

      <!-- 第三行：搜索跳转 -->
      <div class="card p-6">
        <h2 class="text-xl font-semibold text-white mb-4">搜索跳转</h2>
        <div class="flex gap-4">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="输入关键词搜索视频"
            class="input-primary flex-1"
            @keyup.enter="search"
          />
          <div class="flex gap-2">
            <button @click="searchBaidu" class="btn-secondary">
              百度搜索
            </button>
            <button @click="searchEdge" class="btn-secondary">
              Edge搜索
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 云盘选择 -->
    <div class="max-w-4xl mx-auto mt-8">
      <div class="card p-6">
        <h2 class="text-xl font-semibold text-white mb-4">云盘播放</h2>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            v-for="provider in cloudProviders"
            :key="provider.id"
            @click="openCloudDialog(provider)"
            class="flex flex-col items-center p-4 bg-gray-700 hover:bg-gray-600 rounded-lg transition-colors"
          >
            <i :class="[provider.icon, 'text-2xl mb-2']" :style="{ color: provider.color }"></i>
            <span class="text-sm text-gray-300">{{ provider.name }}</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 最近播放 -->
    <div v-if="recentHistory.length > 0" class="max-w-4xl mx-auto mt-8">
      <div class="card p-6">
        <h2 class="text-xl font-semibold text-white mb-4">最近播放</h2>
        <div class="space-y-2">
          <div
            v-for="item in recentHistory"
            :key="item.mediaId"
            class="flex items-center justify-between bg-gray-700 p-3 rounded hover:bg-gray-600 cursor-pointer"
            @click="resumePlay(item)"
          >
            <div class="flex-1">
              <div class="text-sm font-medium text-white">{{ item.title }}</div>
              <div class="text-xs text-gray-400">
                上次播放: {{ formatTime(item.lastPosition) }} / {{ formatTime(item.duration || 0) }}
              </div>
            </div>
            <button class="text-primary-400 hover:text-primary-300">
              <i class="fas fa-play"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMediaStore } from '../stores/media'
import type { CloudProvider, PlaybackHistory } from '../types/media'

const router = useRouter()
const mediaStore = useMediaStore()

const singleUrl = ref('')
const batchUrl = ref('')
const searchQuery = ref('')
const batchItems = ref<Array<{ id: string; url: string }>>([])

const cloudProviders: CloudProvider[] = [
  { id: 'baidu', name: '百度网盘', icon: 'fas fa-cloud', color: '#1890ff' },
  { id: 'aliyun', name: '阿里云盘', icon: 'fas fa-cloud', color: '#ff6a00' },
  { id: 'xunlei', name: '迅雷云盘', icon: 'fas fa-bolt', color: '#00a0e9' },
  { id: 'quark', name: '夸克网盘', icon: 'fas fa-atom', color: '#00b96b' },
]

const recentHistory = computed(() => {
  return mediaStore.playbackHistory
    .slice(-5)
    .reverse()
    .map(h => ({
      ...h,
      title: mediaStore.mediaList.find(m => m.id === h.mediaId)?.title || '未知视频',
      duration: mediaStore.mediaList.find(m => m.id === h.mediaId)?.duration,
    }))
})

const playSingle = () => {
  if (!singleUrl.value.trim()) return
  
  const mediaItem = {
    id: Date.now().toString(),
    title: new URL(singleUrl.value).pathname.split('/').pop() || '未知视频',
    url: singleUrl.value,
    type: 'video' as const,
  }
  
  mediaStore.setCurrentMedia(mediaItem)
  router.push('/player')
}

const addToBatch = () => {
  if (!batchUrl.value.trim()) return
  
  batchItems.value.push({
    id: Date.now().toString(),
    url: batchUrl.value,
  })
  
  batchUrl.value = ''
}

const removeFromBatch = (id: string) => {
  batchItems.value = batchItems.value.filter(item => item.id !== id)
}

const clearBatch = () => {
  batchItems.value = []
}

const playBatch = () => {
  if (batchItems.value.length === 0) return
  
  const mediaItems = batchItems.value.map(item => ({
    id: item.id,
    title: new URL(item.url).pathname.split('/').pop() || '未知视频',
    url: item.url,
    type: 'video' as const,
  }))
  
  mediaStore.mediaList = mediaItems
  mediaStore.setCurrentMedia(mediaItems[0])
  router.push('/batch')
}

const searchBaidu = () => {
  if (!searchQuery.value.trim()) return
  window.open(`https://www.baidu.com/s?wd=${encodeURIComponent(searchQuery.value)}`, '_blank')
}

const searchEdge = () => {
  if (!searchQuery.value.trim()) return
  window.open(`https://cn.bing.com/search?q=${encodeURIComponent(searchQuery.value)}`, '_blank')
}

const openCloudDialog = (provider: CloudProvider) => {
  // 这里可以打开云盘文件选择对话框
  console.log('打开云盘:', provider.name)
}

const resumePlay = (item: PlaybackHistory & { title: string; duration?: number }) => {
  const media = mediaStore.mediaList.find(m => m.id === item.mediaId)
  if (media) {
    mediaStore.setCurrentMedia(media)
    router.push('/player')
  }
}

const formatTime = (seconds: number): string => {
  if (!seconds || seconds === 0) return '00:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>
